package net.zzy.pbbot.plugin.tiktok.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import net.lz1998.pbbot.utils.Msg;
import net.zzy.pbbot.plugin.tiktok.entity.TikTokDaoEntity;
import net.zzy.pbbot.plugin.tiktok.entity.TikTokResp;
import net.zzy.pbbot.plugin.tiktok.mapper.TikTokGirlsMapper;
import net.zzy.pbbot.util.HttpsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static net.zzy.pbbot.finalfield.Api.TIK_TOK_GET;
import static net.zzy.pbbot.finalfield.FinalStr.URL_REX;

/**
 * @author zhuZhaoYang
 * @date 2021/9/25 22:52
 */
@Component
@Service
public class TikTokService {

    private TikTokGirlsMapper tikTokGirlsMapper;

    @Autowired
    public void setTikTokGirlsMapper(TikTokGirlsMapper tikTokGirlsMapper) {
        this.tikTokGirlsMapper = tikTokGirlsMapper;
    }

    public TikTokDaoEntity getTikTokUrl() {
        return tikTokGirlsMapper.selectOneUrlByRand();
    }

    public Msg setTikTokUrl(String rawMessage) throws Exception {
        Pattern pattern = Pattern.compile(URL_REX);
        Matcher matcher = pattern.matcher(rawMessage);
        if (!matcher.find()) {
            return Msg.builder().text("url匹配失败！");
        }
        String url = matcher.group();
        String get = HttpsUtils.get(TIK_TOK_GET + url, null, null);
        TikTokResp tikTokResp = JSON.parseObject(get, TikTokResp.class);
        if (!"success".equals(tikTokResp.getStatus())) {
            return Msg.builder().text("视频解析失败");
        }
        TikTokDaoEntity tikTokDaoEntity = new TikTokDaoEntity();
        tikTokDaoEntity.setUrl(url);
        tikTokDaoEntity.setDesc(tikTokResp.getDesc());
        tikTokDaoEntity.setMp4(tikTokResp.getMp4());
        int insert = tikTokGirlsMapper.insert(tikTokDaoEntity);
        if (insert == 1) {
            return Msg.builder().text("添加成功！").video(tikTokDaoEntity.getMp4(), tikTokDaoEntity.getMp4(), true);
        } else {
            return Msg.builder().text("添加失败！");
        }
    }

    public void deleteUrl(String tikTokUrl) {
        tikTokGirlsMapper.delete(new QueryWrapper<TikTokDaoEntity>().eq("url", tikTokUrl));
    }
}
